const marker = require('../marker/marker');
const like = require('../like/like');

// 获取所有路线
async function getLine(data){
    const offset = ( Number(data.pageNumber) - 1) * 10;
    const pageSize = Number(data.pageSize)
    let selectSql = `SELECT * FROM line ORDER BY updateTime ASC LIMIT ? OFFSET ? `;
    const qlParams = [ pageSize , offset];
    const selectRows = await global.sql(selectSql, qlParams)
    if (selectRows.status) {
        return {
            code: 200,
            msg: '请求成功',
            data: selectRows.data
        }
    }else {
        return {
            code: 500,
            msg: '服务繁忙',
            data: null
        }
    }
}

// 获取我的路线
async function getMyLine(data){
    const offset = (data.pageNumber - 1) * 10;
    let selectSql = `SELECT * FROM line WHERE userId = ? ORDER BY createTime ASC LIMIT ? OFFSET ?`;
    const qlParams = [data.userId, 10, offset];
    let selectRows = await global.sql(selectSql, qlParams)
    if (selectRows.status) {
        return {
            code: 200,
            msg: '请求成功',
            data: selectRows.data
        }
    }else {
        return {
            code: 500,
            msg: '服务繁忙',
            data:  null
        }
    }
   
}

// 查询路线详情
async function getLineDetail(data){
    let selectSql = `SELECT * FROM line WHERE id="${data.id}" `;
    const selectRows = await global.sql(selectSql)
    if (selectRows.status) {
        if (selectRows.data.length === 0) {
            return {
                code: 500,
                msg: '未找到该路线',
                data: null
            }
        }else {
            // 判断当前用户是否是第一次查看这条路线
            await addHistoryByLineIdAndUserId(data)
            // 获取这条路线的预览数量
            const viewingFrequency = await getHistoryTotalDataByLineId(data)
            const lineDetail = selectRows.data[0]
            // 获取当前路线被收藏的次数
            const likeTotal = await like.getLikeByLineId(data.id)
            // 获取当前路线的所有 markerArr
            const markerArr = await marker.getMarkerListByLineId(data.id)
            return {
                code: 200,
                msg: '请求成功',
                data: {
                    ...lineDetail,
                    marker: markerArr,
                    viewingFrequency: viewingFrequency,
                    likeTotal: likeTotal
                }
            }
        }
    }else {
        return {
            code: 500,
            msg: '未找到该路线',
            data: null
        }
    }
}

// 添加路线
async function addLine(data){
    const { name, briefIntroduction, address, userId, userName } = data
    if (!name) {
        return {code: 500, msg: '缺少名称', data: null}
    }else if (!address) {
        return {code: 500, msg: '缺少地点', data: null}
    }else {
        const dateTime = global.commonFun.getNowTime()
        let addSql = `INSERT INTO line(name,userId,address,createByName,briefIntroduction,createTime,updateTIme) VALUES(?,?,?,?,?,?,?)`
        const addSqlParams = [name, userId, address, userName,briefIntroduction, dateTime, dateTime];
        const addRow = await global.sql(addSql,addSqlParams)
        if (addRow.status) {
            return {code: 200, msg: '添加成功', data: null}
        }else {
            return {code: 500, msg: '服务繁忙', data: null}
        }
    }
}

// 保存两个 marker 点之间的路线
async function saveMarkerSteps(data) {
    const {
        userId, originLatitude, originLongitude, destinationLongitude,
        destinationLatitude, step, originMarkerId, destinationMarkerId, lineId
    } = data
    const dateTime = global.commonFun.getNowTime()
    const addSqlParams = [userId,originLatitude, originLongitude, destinationLongitude,destinationLatitude, step,originMarkerId, destinationMarkerId,dateTime, lineId];
    const str = `userId,originLatitude,originLongitude,destinationLongitude,destinationLatitude,step,originMarkerId,destinationMarkerId,createTime,lineId`
    const addStr = global.commonFun.addSqlStr(str)
    let addSql = `INSERT INTO step(${str}) VALUES(${addStr})`
    const addRow = await global.sql(addSql,addSqlParams)
    if (addRow.status) {
        return {code: 200, msg: '添加成功', data: null}
    }else {
        return {code: 500, msg: '服务繁忙', data: null}
    }
}

// 编辑路线
async function editLine(data) {

}

// 删除路线
async function delLine(data) {
    let delSql = `DELETE FROM line WHERE lineId = ${data.id}`
    let delMarkerSql = `DELETE FROM marker WHERE lineId = ${data.id}`
    let delStepSql = `DELETE FROM step WHERE lineId = ${data.id}`
    const arr = await Promise.all([global.sql(delSql), global.sql(delMarkerSql), global.sql(delStepSql)])
    const statusArr = arr.map(item => {
        return item.status
    })
    if (statusArr.includes(false)) {
        return {code: 500, msg: '服务器繁忙', data: null}
    }else {
        return {
            code: 200,
            msg: '删除成功',
            data: null
        }
    }
}

// 最近一次编辑的路线
async function getLastEditedRoute(data) {
    const { userId } = data
    const selectSql = `SELECT *  FROM line  WHERE userId = ${userId}  ORDER BY updateTime DESC  LIMIT 1`
    const selectRow = await global.sql(selectSql)
    if (selectRow.status) {
        return {
            code: 200,
            msg: '请求成功',
            data: selectRow.data
        }
    }else {
        return {
            code: 500,
            msg: '服务繁忙',
            data: null
        }
    }
}

// 查询某条数据的查看纪录
async function getHistoryTotalDataByLineId(data) {
    let checkSql = `SELECT COUNT(*) AS total FROM history WHERE lineId="${data.id}"`
    const selectRow = await global.sql(checkSql)
    if (selectRow.status) {
        return selectRow.data[0].total
    }else {
        return 0
    }
}

// 判断是否是第一次查看该路线，如果是就不添加，如果不是就添加一条记录
async function addHistoryByLineIdAndUserId(data) {
    let checkSql = `SELECT * FROM history WHERE lineId="${data.id}" AND userId="${data.userId}"`
    const historyData = await global.sql(checkSql)
    if (historyData.status) {
        if ( historyData.data.length === 0 ) {
            const dateTime = global.commonFun.getNowTime()
            let addSql =  `INSERT INTO line(userId,lineId,createTime,type) VALUES(?,?,?,?)`
            const addSqlParams = [data.userId, data.id, dateTime, 'line'];
            await global.sql(addSql, addSqlParams)
        }
    }
}

exports.getLine = getLine
exports.getMyLine = getMyLine
exports.addLine = addLine
exports.editLine = editLine
exports.delLine = delLine
exports.getLineDetail = getLineDetail
exports.getLastEditedRoute = getLastEditedRoute
exports.saveMarkerSteps = saveMarkerSteps

